<?php

define('Phase_Sleep', 'Sleep');
define('Phase_Input', 'Input');
define('Phase_Action', 'Action');
define('Phase_Dummy', 'Dummy');
define('Phase_Buy', 'Buy');
define('Phase_Payment', "Payment");
define("Phase_GameOver", "GameOver");
define("Phase_GameResign", "GameResign");
define('Phase_BlackMarketPayment', 'BlackMarketPayment');
define('Phase_DigitalStorePayment', 'DigitalStorePayment');
define('Phase_DigitalStoreBuy', 'DigitalStoreBuy');
define('Phase_Output', 'Output');

//define Lobby Game Phases:
define('Phase_Available', 'Available');
define('Phase_Busy', 'Busy');
define('Phase_InGame', 'InGame');
define('Phase_Away', 'Away');
define('Phase_Disconnected', 'Disconnected');

define('OUTPOST_DONT_CHANGE_PLAYER', 'OUTPOST_DONT_CHANGE_PLAYER');
define('POSSESED_TURN', 'POSSESED_TURN');

define('DrawPile', "DrawPile");
define('DiscardPile', "DiscardPile");
define('PlayHand', "PlayHand");
define('PlayArea', "PlayArea");
define('Trash', "Trash");
define('BoardCards', "BoardCards");
define('Prizes', 'Prizes');
define('Spoils', 'Spoils');
define('Ruins', 'Ruins');
define('Mercenary', 'Mercenary');
define('Madman', 'Madman');
define('IslandPile', 'IslandPile');
define('NativeVillagePile', 'NativeVillagePile');
define('HavenPile', 'HavenPile');
define('DurationPileCards', 'DurationPileCards');
define('HorseTradersPile', 'HorseTradersPile');
define('BlackMarketPile', 'BlackMarketPile');
define('NOPILE', 'NOPILE');

// reaction - things that can happen during a game
define('Buy', 'Buy');
define('Gain', 'Gain');
define('Attack', 'Attack');
define('Trashed', 'Trashed');

// actor - who did the action
define('Yourself', 'Yourself');
define('SomeoneElse', 'SomeoneElse');

// time to play a reaction
define("ForEachCard", "ForEachCard");
define("OncePerReaction", "OncePerReaction");
define("UnlimitedReaction", "UnlimitedReaction");

define('Input_ChooseMany', 'ChooseMany');
define('Input_ChooseOne', 'ChooseOne');
define('Input_Reorder', 'ChooseReorder');

define('RETURN_DURATION_TO_DISCARD', 3141592);
define('DELETE_VIRTUAL_DURATION_CARD', -3141592);
define('REAL_CARD', 1);
define('VIRTUAL_CARD', -1);

define('NEW_LINE', "NEW_LINE");

define('UNDO_PLAY_TREASURE', 'UNDO_PLAY_TREASURE');
define('UNDO_BUY_CARD', 'UNDO_BUY_CARD');
define('UNDO_BUY_PHASE', 'UNDO_BUY_PHASE');
define('UNDO_PLAY_ACTION', 'UNDO_PLAY_ACTION');
define('UNDO_PLAY_REACTION', 'UNDO_PLAY_REACTION');
define('UNDO_BLOCK', 'UNDO_BLOCK');

// should consider multiple games/rooms in multiple windows
function getRoomId() {

    $user = getUserId();
    $db = DBUtils::Create();
    $rooms = $db->getAllRoomsForPlayer($user);
    if (count($rooms) == 1) { //player should only be in one room
        return $rooms[0]['RoomID'];
    }
    if (!isset($_SESSION['roomid'])) // In case something went wrong with the db, but the session still retains valid data
        return 0;

    return $_SESSION['roomid'];
}

function getUserId() {
    if (!isset($_SESSION['id']))
        return null;
    return $_SESSION['id'];
}

function getCommand() {
    list($command) = getParams('cmd');
    return $command;
}

function setRoom($room, $userid) {
    $db = DBUtils::Create();
    $id = 0;
    if (is_object($room))
        $id = $room->getId();
    else
        $id = $room;

    $db->addToRoom($id, $userid);
}

function loadGame() {
    $gid = getRoomId();
    if ($gid > 0) {
        $db = DBUtils::Create();
        $game = $db->LoadGame($gid);
        $game->runInfluenceCards();
        return $game;
    } else {
        $lobby = loadLobby();
        return $lobby;
    }
}

function loadLobby() {
    $lobby = Lobby::GetLobby();
    return $lobby;
}

function getUniqueCards($cards) {
    $unique = array();
    foreach ($cards as $card) {
        if (!array_key_exists($card->getKey(), $unique)) {
            $unique[$card->getKey()] = $card;
        }
    }
    return array_values($unique);
}

//going over the parameters and checking that they all appear in the request
//will return an error if one of the parameters missing
function checkParams() {

    $argv = func_get_args();
    foreach ($argv as $arg) {
        if (!(array_key_exists($arg, $_REQUEST))) {
            throw new Exception("$arg not set");
        }
        if ($_REQUEST[$arg] == "") {
            throw new Exception("$arg not set");
        }
    }
    return false;
}

//setting all the parameters from the request to the variables, if not found setting null
function getParams() {
    $argv = func_get_args();
    $results = array();
    $argv = func_get_args();
    foreach ($argv as $arg) {
        if ((array_key_exists($arg, $_REQUEST)) && ($_REQUEST[$arg] != "")) {
            $results[] = $_REQUEST[$arg];
        } else {
            $results[] = null;
        }
    }
    return $results;
}

function checkPermissions() {
    return true;
}

function getCardNames($cards) {
    $res = array();
    if ($cards) {
        foreach ($cards as $c) {
            if (is_array($c)) {
                $c = $c['card'];
            }
            $res[] = $c->getValue();
        }
    }
    return $res;
}

function getPileByName($game, $player, $name) {
    if ($name == DiscardPile)
        return $player->piles->discardPile;
    if ($name == DrawPile)
        return $player->piles->drawPile;
    if ($name == PlayHand)
        return $player->piles->playHand;
    if ($name == PlayArea)
        return $player->piles->playArea;
    if ($name == Trash)
        return $game->board->trash;

    throw new Exception("Unsupported pile");
}

function getQuantityPileData(Game $game, $pile) {
    $data = array();

    foreach ($pile as $card_arr) {
        $card_data = array();
        if (array_key_exists('subPile', $card_arr) && sizeof($card_arr['subPile']) > 0) {

            $card_data = $card_arr['subPile'][0]->getData($game);
        } else {
            $card_data = $card_arr['card']->getData($game);
        }
        $card_data['quantity'] = $card_arr['quantity'];

        $data[] = $card_data;
    }
    return $data;
}

function beautifyString($full_line) {
    $l = array();
    $line_tokens = explode("|", $full_line);
    $l['line'] = $line_tokens[0];
    $params = array();
    $k = 0;
    for ($j = 1; $j < sizeof($line_tokens); $j++) {
        $param_tokens = explode("~", $line_tokens[$j]);
        #this is not a param token that we want, so we append it to the regular line
        if (sizeof($param_tokens) < 2) {
            $l['line'] .= $line_tokens[$j];
            continue;
        }
        $params[$k]['name'] = $param_tokens[0];
        $params[$k]['d_name'] = $param_tokens[1];
        $k++;
    }
    $l['params'] = $params;
    return $l;
}

function getPileData($game, $pile) {
    $data = array();
    foreach ($pile as $card) {
        $data[] = $card->getData($game);
    }

    return $data;
}

function prepare($card) {
    if ($card === null)
        return null;
    if (!is_object($card)) {
        $card = n2c($card);
    }
    return $card;
}

function n2c($card_name) {
    #var_dump(gettype($card_name));
    #if (gettype($card_name) == 'boolean')
    #	var_dump(debug_backtrace());
    $class_name = Game::$n2cArray[$card_name];
    return new $class_name;
}

function prefix($card_name, $quantity) {
    $vowels = array('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U');
    if ($quantity == 1) {
        if (in_array($card_name[0], $vowels))
            return "an";
        return "a";
    }
    else
        return "";
}

function niceReadableString(Game $game, $cards, $name = null, $addVictoryPoints = false) {
    if ($cards === null) {
        return "nothing";
    }

    if (!is_array($cards)) {
        $cards = array($cards);
    }

    $msg = "";
    if (sizeof($cards) == 0) {
        $msg = "nothing";
    } else {

        $cards_data = "";
        $cards_dic_quantity = array();
        $cards_dic = array();
        $msg = "";
        for ($i = 0; $i < sizeof($cards); $i++) {
            $card = $cards[$i];
            if (!is_object($card))
                $card = n2c($card);

            $cv = $card->getValue();
            if (!array_key_exists($cv, $cards_dic_quantity)) {
                $cards_dic_quantity[$cv] = 0;
                $cards_dic[$cv] = $card;
            }

            $cards_dic_quantity[$cv] += 1;
        }

        $j = 0;
        $keys = array_keys($cards_dic_quantity);
        foreach ($keys as $k) {
            $card = $cards_dic[$k];
            $quantity = $cards_dic_quantity[$k];

            $d_name = $card->getDisplayName($quantity);

            if ($j == 0) {
                $msg .= $d_name;
            } else if ($j == sizeof($cards_dic_quantity) - 1) {
                $msg .= " and " . $d_name;
            } else {
                $msg .= ", " . $d_name;
            }

            if ($addVictoryPoints) {
                $vp = $game->getVictoryPoints($card, $name);
                $msg .= " * $vp vp";
            }
            $j += 1;
        }
    }
    return $msg;
}

function nicePrint($cards) {
    if ($cards === null) {
        ScreenDisplay::$LMSG = "nothing";
        return "nothing";
    }

    if (!is_array($cards)) {
        $cards = array($cards);
    }

    $msg = "";
    if (sizeof($cards) == 0) {
        $msg = "nothing";
    } else {

        $cards_data = "";
        $cards_dic_quantity = array();
        $cards_dic = array();
        $msg = "";
        for ($i = 0; $i < sizeof($cards); $i++) {
            $card = $cards[$i];
            if (!is_object($card))
                $card = n2c($card);

            $cv = $card->getValue();
            if (!array_key_exists($cv, $cards_dic_quantity)) {
                $cards_dic_quantity[$cv] = 0;
                $cards_dic[$cv] = $card;
            }

            $cards_dic_quantity[$cv] += 1;
        }
        ksort($cards_dic_quantity);
        $j = 0;
        $keys = array_keys($cards_dic_quantity);
        foreach ($keys as $s) {
            $prefix = prefix($s, $cards_dic_quantity[$s]);
            if ($j == 0) {
                $msg .= $prefix . " [!]";
            } else if ($j == sizeof($cards_dic_quantity) - 1) {
                $msg .= " and " . $prefix . " [!]";
            } else {
                $msg .= ", " . $prefix . " [!]";
            }
            $cards_data .= $cards_dic[$s]->getDataAsStr($cards_dic_quantity[$s]) . "|";
            $j += 1;
        }

        $msg .= "|" . $cards_data;
    }
    ScreenDisplay::$LMSG = $msg;
    return $msg;
}

foreach (Game::$ALL_KINGDOM as $card) {
    $card = new $card;
    $key = $card->getKey();
    $val = $card->getValue();
    Game::$c2nArray[$key] = $val;
    Game::$n2cArray[$val] = $key;
}

foreach (Game::$ALL_OTHER as $card) {
    $card = new $card;
    $key = $card->getKey();
    $val = $card->getValue();
    Game::$c2nArray[$key] = $val;
    Game::$n2cArray[$val] = $key;
}

foreach (Game::$PRIZES as $card) {
    $card = new $card;
    $key = $card->getKey();
    $val = $card->getValue();
    Game::$c2nArray[$key] = $val;
    Game::$n2cArray[$val] = $key;
}

foreach (Game::$SHELTERS as $card) {
    $card = new $card;
    $key = $card->getKey();
    $val = $card->getValue();
    Game::$c2nArray[$key] = $val;
    Game::$n2cArray[$val] = $key;
}

foreach (Game::$RUINS as $card) {
    $card = new $card;
    $key = $card->getKey();
    $val = $card->getValue();
    Game::$c2nArray[$key] = $val;
    Game::$n2cArray[$val] = $key;
}

foreach (Game::$KNIGHTS as $card) {
    $card = new $card;
    $key = $card->getKey();
    $val = $card->getValue();
    Game::$c2nArray[$key] = $val;
    Game::$n2cArray[$val] = $key;
}

foreach (Game::$DARKAGES_NOT_IN_SUPLY as $card) {
    $card = new $card;
    $key = $card->getKey();
    $val = $card->getValue();
    Game::$c2nArray[$key] = $val;
    Game::$n2cArray[$val] = $key;
}

function alertPlayer($name, $alert = 1) {
    $db = DBUtils::Create();
    $db->setAlert($name, $alert);
}

function DEBUG($s, $logTrace = true) {
    $myFile = "testFile.txt";
    $fh = fopen($myFile, 'a');
    fwrite($fh, $s);
    fwrite($fh, "\r\n");
    if ($logTrace) {
        $bt = debug_backtrace();
        foreach ($bt as $t) {
            if (isset($t['file']) && isset($t['line']))
                fwrite($fh, "file: " . $t['file'] . "\r\n" . "line: " . $t['line'] . "\r\n");
        }
    }
    fclose($fh);
}

?>